package ttOrder.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import ttOrder.service.UserServiceImpl;
import ttOrder.util.CookieUtil;

public class LoginInterceptor implements HandlerInterceptor {

	@Resource
	private UserServiceImpl userService;
	
	/**
	 * 用来存储不拦截的路径
	 */
	private static final String[] ignore_URI = { "/ttOrder/login","/ttOrder/homePage"};
	private static final String[] front = {"/ttOrder/index","/ttOrder/menu"};
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception e)
			throws Exception {
		System.out.println("----------- LoginInterceptor.afterCompletion()-------------");		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		System.out.println("------------LoginInterceptor.postHandle()---------------");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		boolean flag = false;
		String servletPath = request.getServletPath();
		System.out.println("请求路径是：" + servletPath);
		// 检测是否需要拦截的请求
		for (String s : ignore_URI) {
			if (servletPath.contains(s)) {
				System.out.println("该请求不需要拦截");
				flag = true;
			}
		}
		// 需要拦截处理的请求
		if (!flag) {
			// 获取存储在cookie域的用户
			String userId = null;
			userId = CookieUtil.getUserIdFromCookie(request);
			if(userId == null){
				userId = "null";
			}
			if (userId.equals("null") || userId.equals(null)) {
				System.out.println("拦截请求：用户未登录，禁止直接访问，返回登录界面");
				request.setAttribute("message", "请先登录");
				// 服务器内部转发，可以带回request
				boolean isFront = false;
				for (String s : front) {
					if (servletPath.contains(s)) {
						isFront = true;
					}
				}	
				if (isFront) {
					request.getRequestDispatcher("/homePage").forward(request, response);
				}
				else{
					request.getRequestDispatcher("/login").forward(request, response);
				}
			} else {
				System.out.println(userId);
				System.out.println("拦截请求：用户已经登录，可以浏览‘吃了吗’");
				flag = true;
			}
		}
		return flag;
		/*HttpSession session = request.getSession();
		UserVO user = (UserVO) session.getAttribute("user");
		if (user != null) {
			return true;
		} else {
			response.sendRedirect(request.getContextPath() + "/login");
		}
		System.out.println("-------------LoginInterceptor.preHandle()---------------");
		return false;*/
	}
}
